package com.lb.statck.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import java.io.InputStream;

public class OssUtil {

    /**
     * 上传文件到阿里云OSS
     * @param bucketName Bucket名称
     * @param endpoint OSS Endpoint
     * @param accessKeyId AccessKeyId
     * @param accessKeySecret AccessKeySecret
     * @param objectName OSS中的文件路径
     * @param inputStream 文件的输入流
     * @return 上传结果
     */
    public static String uploadFile(String bucketName, String endpoint, String accessKeyId, String accessKeySecret, String objectName, InputStream inputStream) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            System.out.println("文件上传成功，ETag: " + result.getETag());

            // 生成文件的访问URL
            String fileUrl = "https://"+  bucketName+"."+ endpoint  + "/" + objectName;
            return fileUrl;
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败: " + e.getMessage();
        } finally {
            // 关闭OSS客户端
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}